<template>
    <div class="primitive-pick">
        <h3>Primitive几何形体选取</h3>
        <div class="pick-info">
            <p><strong>说明：</strong>多个GeometryInstance合并后仍可单独选取</p>
            <p>通过Scene.pick可以获取鼠标点击位置的对象</p>
        </div>
        <div class="pick-controls">
            <button @click="createSelectableShapes" class="create-btn">创建可选形状</button>
            <button @click="enablePicking" class="pick-btn">启用选取模式</button>
            <button @click="disablePicking" class="disable-btn">禁用选取模式</button>
            <button @click="clearSelectableShapes" class="clear-btn">清除形状</button>
        </div>
        <div class="pick-status">
            <p v-if="isPickingEnabled">选取模式：已启用</p>
            <p v-else>选取模式：已禁用</p>
            <p v-if="lastPickedObject">最后选取：{{ lastPickedObject }}</p>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, inject, onMounted, onUnmounted } from 'vue';
import { XbsjEarthUi } from '../../../../scripts/xbsjEarthUi';
import PrimitiveManager from './primitiveManager';

const xbsjEarthUi = inject('xbsjEarthUi') as XbsjEarthUi;
const isPickingEnabled = ref(false);
const lastPickedObject = ref('');
let handler: any = null;
let currentPrimitive: any = null; // 存储当前创建的Primitive
const primitiveManager = PrimitiveManager.getInstance();

// 获取EarthUI中的Cesium原生Viewer实例
const getCesiumViewer = () => {
    return xbsjEarthUi.activeViewer?.innerViewer?.viewer;
};

// 创建可选取的形状
const createSelectableShapes = () => {
    const viewer = getCesiumViewer() as any;
    if (!viewer) return;

    try {
        // 创建矩形实例（北京）
        const rectangleInstance = new (window as any).Cesium.GeometryInstance({
            geometry: new (window as any).Cesium.RectangleGeometry({
                rectangle: (window as any).Cesium.Rectangle.fromDegrees(115.5, 39.5, 116.5, 40.5),
                vertexFormat: (window as any).Cesium.PerInstanceColorAppearance.VERTEX_FORMAT
            }),
            attributes: {
                color: (window as any).Cesium.ColorGeometryInstanceAttribute.fromColor((window as any).Cesium.Color.RED)
            },
            id: 'rectangle-1'
        });

        // 创建圆形实例（上海）
        const circleInstance = new (window as any).Cesium.GeometryInstance({
            geometry: new (window as any).Cesium.CircleGeometry({
                center: (window as any).Cesium.Cartesian3.fromDegrees(121.0, 31.0),
                radius: 200000.0,
                vertexFormat: (window as any).Cesium.PerInstanceColorAppearance.VERTEX_FORMAT
            }),
            attributes: {
                color: (window as any).Cesium.ColorGeometryInstanceAttribute.fromColor((window as any).Cesium.Color.BLUE),
                show: (window as any).Cesium.ShowGeometryInstanceAttribute(true)
            },
            id: 'circle-1'
        });

        // 创建椭球体实例（广州）
        const ellipsoidGeometry = new (window as any).Cesium.EllipsoidGeometry({
            radii: new (window as any).Cesium.Cartesian3(150000.0, 150000.0, 150000.0),
            vertexFormat: (window as any).Cesium.PerInstanceColorAppearance.VERTEX_FORMAT
        });

        const ellipsoidInstance = new (window as any).Cesium.GeometryInstance({
            geometry: ellipsoidGeometry,
            modelMatrix: (window as any).Cesium.Matrix4.multiplyByTranslation(
                (window as any).Cesium.Transforms.eastNorthUpToFixedFrame(
                    (window as any).Cesium.Cartesian3.fromDegrees(113.0, 23.0)
                ),
                new (window as any).Cesium.Cartesian3(0.0, 0.0, 300000.0),
                new (window as any).Cesium.Matrix4()
            ),
            attributes: {
                color: (window as any).Cesium.ColorGeometryInstanceAttribute.fromColor((window as any).Cesium.Color.GREEN)
            },
            id: 'ellipsoid-1'
        });

        // 创建Primitive
        const primitive = new (window as any).Cesium.Primitive({
            geometryInstances: [rectangleInstance, circleInstance, ellipsoidInstance],
            appearance: new (window as any).Cesium.PerInstanceColorAppearance({
                translucent: false,
                closed: true
            })
        });

        viewer.scene.primitives.add(primitive);
        currentPrimitive = primitive; // 保存引用
        primitiveManager.addPrimitive(primitive); // 添加到全局管理器
        console.log('可选取形状创建成功');
    } catch (error) {
        console.error('创建可选取形状失败:', error);
    }
};

// 启用选取模式
const enablePicking = () => {
    const viewer = getCesiumViewer() as any;
    if (!viewer || isPickingEnabled.value) return;

    try {
        handler = new (window as any).Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        
        handler.setInputAction((movement: any) => {
            const pick = viewer.scene.pick(movement.position);
            if ((window as any).Cesium.defined(pick)) {
                if (pick.id === 'rectangle-1') {
                    lastPickedObject.value = '矩形被选取';
                    console.log('矩形被选取');
                    alert('矩形被选取!');
                } else if (pick.id === 'circle-1') {
                    lastPickedObject.value = '圆形被选取';
                    console.log('圆形被选取');
                    alert('圆形被选取!');
                } else if (pick.id === 'ellipsoid-1') {
                    lastPickedObject.value = '椭球体被选取';
                    console.log('椭球体被选取');
                    alert('椭球体被选取!');
                } else {
                    lastPickedObject.value = '未知对象被选取';
                    console.log('未知对象被选取');
                }
            } else {
                lastPickedObject.value = '未选取到对象';
                console.log('未选取到对象');
            }
        }, (window as any).Cesium.ScreenSpaceEventType.LEFT_CLICK);

        isPickingEnabled.value = true;
        console.log('选取模式已启用');
    } catch (error) {
        console.error('启用选取模式失败:', error);
    }
};

// 禁用选取模式
const disablePicking = () => {
    if (handler) {
        handler.destroy();
        handler = null;
    }
    isPickingEnabled.value = false;
    lastPickedObject.value = '';
    console.log('选取模式已禁用');
};

// 清除可选取形状
const clearSelectableShapes = () => {
    const viewer = getCesiumViewer() as any;
    if (!viewer) return;

    try {
        // 只清除全局管理器中的Primitive
        primitiveManager.clearAllPrimitives(viewer);
        currentPrimitive = null;
        lastPickedObject.value = '';
        console.log('可选取形状已清除');
    } catch (error) {
        console.error('清除可选取形状失败:', error);
    }
};

onMounted(() => {
    // 组件加载时检查选取状态
    console.log('Primitive选取组件已加载');
});

onUnmounted(() => {
    // 组件卸载时清理事件处理器
    disablePicking();
});
</script>

<style scoped>
.primitive-pick {
    width: 280px;
    box-sizing: border-box;
    padding: 10px;
}

.pick-info {
    box-sizing: border-box;
    font-size: 14px;
    padding: 10px;
    background-color: #000000;
    border-radius: 4px;
    margin-bottom: 15px;
}

.pick-controls {
    display: flex;
    flex-direction: column;
    margin-bottom: 15px;
}

.create-btn, .pick-btn, .disable-btn, .clear-btn {
    margin-bottom: 8px;
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
}

.create-btn {
    background-color: #2196F3;
    color: white;
}

.create-btn:hover {
    background-color: #1976D2;
}

.pick-btn {
    background-color: #4CAF50;
    color: white;
}

.pick-btn:hover {
    background-color: #45a049;
}

.disable-btn {
    background-color: #FF9800;
    color: white;
}

.disable-btn:hover {
    background-color: #F57C00;
}

.clear-btn {
    background-color: #f44336;
    color: white;
}

.clear-btn:hover {
    background-color: #d32f2f;
}

.pick-status {
    padding: 10px;
    background-color: #000000;
    border-radius: 4px;
    border-left: 4px solid #FF9800;
    color: #FF9800;
    font-weight: bold;
}
</style>
